var _class, _temp;

import Taro from '@tarojs/taro-rn';
import React from 'react';
import { Component } from "@tarojs/taro-rn";
import { View, Image } from "@tarojs/components-rn";
import { host, showToast, uploadPath, getToken } from "../utils/common";
import ImgUploadStyleSheet from "./ImgUpload_styles";
/**
 *
 */
var _styleSheet = ImgUploadStyleSheet;
let ImgUpload = (_temp = _class = class ImgUpload extends Component {
  constructor() {
    super(...arguments);

    this.imgUpload = () => {
      Taro.chooseImage({
        sourceType: ['album', 'camera'],
        count: 1,
        sizeType: ['compressed']
      }).then(res => {
        let tempFiles = res.tempFiles[0];
        // 压缩图片
        // console.log(res)
        Taro.showLoading({ title: '图片上传中...' });
        this.imgCompressed(tempFiles.path, tempFiles.size, blobFile => {
          Taro.uploadFile({
            url: host + uploadPath,
            filePath: blobFile,
            name: 'file',
            header: getToken()
          }).then(imgRes => {
            Taro.hideLoading();
            if (imgRes.statusCode != 200) {
              showToast('上传图片失败,错误原因: ' + imgRes.errMsg);
              return;
            }
            // 图片正确上传
            let imgPath = JSON.parse(imgRes.data).result;
            this.setState({ imgUpload: imgPath });
          }).catch(err1 => {
            Taro.hideLoading();
            console.error(err1);
            showToast('上传图片失败,请稍后重试~');
          });
        });
      }).catch(err => {
        console.error(err);
        showToast('打开图片失败,请稍后重试~');
      });
    };

    this.imgCompressed = (imgPath, imgSize, callBack) => {
      let quality = 1;
      // 大于1M的压缩
      let sizeM = imgSize / 1024 / 1024;
      console.log(sizeM);
      if (sizeM < 1) {
        // 不压缩
        quality = 1;
        callBack(imgPath);
        return;
      } else if (sizeM >= 1 && sizeM < 2) {
        quality = 0.95;
      } else if (sizeM >= 2 && sizeM < 3) {
        quality = 0.92;
      } else {
        quality = 0.8;
      }
      let image = document.createElement('img');
      image.crossOrigin = 'Anonymous';
      console.log(image);
      image.onload = function () {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
        /**
         * 1、本来打算使用toBlob函数进行压缩，因为Taro的chooseImage函数返回的图片路径是blob类型的文件，可是toBlob函数不知道什么原因，并不能返回blob文件。于是打算转换成base64
         * 的图片，没想到也是可以上传的
         * 2、后来真机测试发觉想太多，在pc上能上传，但在手机上并不能上传，还是得转化成blob文件
         *
         */
        // 转化成blob文件
        // 第一个参数回调，第二个参数图片类型(image/png; image/jpeg)默认为image/png；第三个参数图片质量（0~1）取值
        canvas.toBlob(blobFile => {
          // console.log(blobFile)
          // blob数据转化成url数据
          let url = URL.createObjectURL(blobFile);
          // console.log(url)
          callBack && callBack(url);
        }, 'image/jpeg', quality);
        /*let dataUrl = canvas.toDataURL('image/jpeg', quality)
        if(!dataUrl) { showToast('图片上传压缩失败, 请重试！'); return }
        callBack&&callBack(dataUrl)*/
      };
      image.src = imgPath;
    };

    this.imgPreView = imgPath => {
      let imgArr = [imgPath];
      Taro.previewImage({
        urls: imgArr,
        current: '0'
      });
    };

    this.state = {
      imgUpload: ''
    };
  }
  componentWillMount() {}
  /**
   * @param imgField 图片字段名称
   */
  imgDelete(imgField) {
    this.setState({ [imgField]: '' });
    // 后期有删除接口的话待完善
  }
  render() {
    let { imgUpload } = this.state;
    return <View style={_styleSheet["img-upload"]}>
        {imgUpload && <View style={_styleSheet["img-upload__btn"]}>
             <View onClick={this.imgPreView.bind(this, imgUpload)} style={_styleSheet["img-upload__view"]} />
             <View onClick={this.imgDelete.bind(this, 'imgUpload')} style={_styleSheet["img-upload__delete"]} />
          </View>}
          <View onClick={this.imgUpload.bind(this)} style={_styleSheet["img-upload__con"]}>
            {imgUpload && <Image src={imgUpload} style={_styleSheet["img-upload__img"]} />}
          </View>
      </View>;
  }
}, _class.config = {
  navigationBarTitleText: '文件上传'
}, _temp);
export { ImgUpload as default };